package com.munhrasoft.dinamica.business.logic;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.read.biff.BiffException;

import com.munhrasoft.dinamica.business.entities.CheckListHeader;
import com.munhrasoft.dinamica.business.entities.CheckListLines;

@Stateless
public class CheckListEJB {

    @PersistenceContext(unitName = "dinamicaPU")
    private EntityManager em;

    @SuppressWarnings("unchecked")
    public List<CheckListHeader> findChkListByProcess(String oper, String tipo, String modal1,
            String modal2) {
        Query query = em.createNamedQuery("findByProcess");
        query.setParameter("tipo", tipo.toUpperCase());
        query.setParameter("oper", oper.toUpperCase());
        query.setParameter("modal1", modal1.toUpperCase());
        query.setParameter("modal2", modal2.toUpperCase());
        return query.getResultList();
    }
    
    @SuppressWarnings("unchecked")
    public List<CheckListHeader> findChkListByTitulo(String titulochk) {
        Query query = em.createNamedQuery("findByChkTitulo");
        query.setParameter("titulo", titulochk.toUpperCase());
        return query.getResultList();
    }

    @SuppressWarnings("unchecked")
    public List<CheckListHeader> fetchAllChkList() {
        Query query = em.createNamedQuery("findAllChkHeaders");
        return query.getResultList();
    }

    public CheckListHeader createChkHeader(CheckListHeader chkHeader) {
        em.persist(chkHeader);
        return chkHeader;
    }

    public CheckListHeader updateCheckListHeader(CheckListHeader chkHeader) {
        return em.merge(chkHeader);
    }

    public void removeCheckListHeader(CheckListHeader chkHeader) {
        // Remover todas as lines tem que ver como isso funciona, tem que ver como vai
        // fazer cascata de remocao
        em.remove(em.merge(chkHeader));
    }

    public void addCheckLine(CheckListHeader chkHeader, CheckListLines chkList) {
        chkHeader.getCheckLines().add(chkList);
    }

    public void removeCheckLine(CheckListHeader chkHeader, CheckListLines chkList) {
        chkHeader.getCheckLines().remove(chkList);
        updateCheckListHeader(chkHeader);
    }

    public void updateCheckLine(CheckListLines chkList) {
        em.merge(chkList);
    }

    public void carregaCheckListDoExcel(InputStream is) {

        List<CheckListHeader> chkHeaderList = fetchAllChkList();
        if (!chkHeaderList.isEmpty()) {
            // Verifica se existe checklist carregado e apaga todos
            // faz a nova carga
            for (CheckListHeader chkHeader : chkHeaderList) {
                this.removeCheckListHeader(chkHeader);
            }
        }

        Workbook wk = null;
        WorkbookSettings ws = new WorkbookSettings();
        ws.setEncoding("Cp1252");

        try {
            wk = Workbook.getWorkbook(is, ws);
        } catch (BiffException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // initContainer();
        System.out.println("Numero de abas " + wk.getSheets().length);
        String tituloGrupo = new String();

        for (int abaCount = 0; abaCount < wk.getNumberOfSheets(); abaCount++) {

            CheckListHeader chkHeader = new CheckListHeader();
            chkHeader.setCheckLines(new ArrayList<CheckListLines>());
            Sheet chkSheet = wk.getSheets()[abaCount];
            chkSheet.getCell(0, 0).getContents();
            System.out.println("Titulo " + chkSheet.getCell(0, 0).getContents());
            chkHeader.setTitulo(chkSheet.getCell(0, 0).getContents());

            System.out.println("Operacao " + chkSheet.getCell(1, 1).getContents());
            System.out.println("Tipo " + chkSheet.getCell(1, 2).getContents());
            System.out.println("Modalidade1 " + chkSheet.getCell(1, 3).getContents());
            System.out.println("Modalidade2 " + chkSheet.getCell(1, 4).getContents());

            chkHeader.setOperacao(chkSheet.getCell(1, 1).getContents());
            chkHeader.setTipo(chkSheet.getCell(1, 2).getContents());
            chkHeader.setModalidade1(chkSheet.getCell(1, 3).getContents());
            chkHeader.setModalidade2(chkSheet.getCell(1, 4).getContents());

            this.createChkHeader(chkHeader);

            int linesCount = PrimeiraCargaEJB.HEADER_LINES;

            while (linesCount < chkSheet.getRows()) {

                CheckListLines chkLine = new CheckListLines();

                if ("GRUPO".equals(chkSheet.getCell(1, linesCount).getContents())) {
                    tituloGrupo = new String(chkSheet.getCell(0, linesCount).getContents());
                    chkLine.setDescricao(chkSheet.getCell(0, linesCount + 1).getContents());
                    linesCount = linesCount + 2;
                } else {
                    chkLine.setDescricao(chkSheet.getCell(0, linesCount).getContents());
                    linesCount++;
                }

                chkLine.setGrupo(tituloGrupo);

                System.out.println("Grupo " + chkLine.getGrupo());
                System.out.println("Descricao " + chkLine.getDescricao());

                this.addCheckLine(chkHeader, chkLine);

            }

            this.updateCheckListHeader(chkHeader);
        }
    }

}
